package com.school.hjt.schoolclasscard.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.google.gson.Gson;
import com.school.hjt.schoolclasscard.BaseApplication;
import com.school.hjt.schoolclasscard.IMyAidlInterface;
import com.school.hjt.schoolclasscard.R;
import com.school.hjt.schoolclasscard.bean.ResultFy;
import com.school.hjt.schoolclasscard.db.CardDao;
import com.school.hjt.schoolclasscard.db.StudentSign;
import com.school.hjt.schoolclasscard.utlis.APPUtlis;
import com.school.hjt.schoolclasscard.utlis.AsyncTaskSoapUtil;
import com.school.hjt.schoolclasscard.utlis.ClassCalendar;
import com.school.hjt.schoolclasscard.utlis.Constant;
import com.school.hjt.schoolclasscard.utlis.OkhttPost;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by xqx on 2017/11/10.
 *
 */

public class RemoteService extends Service {
    private MyBinder binder;
    private ServiceConnection conn;
    Intent intent = new Intent();
    @Override
    public void onCreate() {
        super.onCreate();
        // System.out.println("远程进程开启");
        init();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (Constant.isTS){
                    StudentSign();
                }else{
                    TeacherSign();
                }
            }
        },8000,4000);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String etherNetIP = APPUtlis.getEtherNetIP();
                if (etherNetIP.equals("0.0.0.0")){
                    try {
                        APPUtlis.down();
                        APPUtlis.up();
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"  IP:"+etherNetIP);
                        sendBroadcast(intent);
                    } catch (IOException e) {
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"IP出错"+e.toString());
                        sendBroadcast(intent);
                        e.printStackTrace();
                    }
                }else{
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"  IP:"+etherNetIP);
                        sendBroadcast(intent);
                }
                Heartbeat();
            }
        },8000,120000);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intents = new Intent();
        intents.setClass(this, LocalService.class);
        bindService(intents, conn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

    private void init() {
        if (conn == null) {
            conn = new MyConnection();
        }
        binder = new MyBinder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    static class MyBinder extends IMyAidlInterface.Stub {
        @Override
        public String getName() throws RemoteException {
            return "远程连接";
        }
    }
    class RCall implements OkhttPost.Callback{
        @Override
        public void onError(Call call, Exception e, int id) {
            if (id==2){
                intent.setAction(Constant.ERR);
                intent.putExtra(Constant.ERR, ClassCalendar.getStringtHour()+": 走读数据接口访问失败"+e.toString());
                sendBroadcast(intent);
            }
        }
        @Override
        public void onResponse(String response, int id) {

        }
    }
    //打卡考勤
    public void Timecard(String str2,AsyncTaskSoapUtil.Callback callback){
        String time= ClassCalendar.getCardtime();

        String namespace = "http://www.gcihjt.com/";//namespace
        String methodName = "UploadSwingCards";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        Log.e("debug",time);
        String md5="hjt"+time+"256B07301378445C83CB1A4D021FF4C7";
//        String md51 = AppUtlis.md5(md5);
        String md5Value = APPUtlis.getMd5Value(md5);
        Log.e("debug12",md5Value);
        map.put("Xml",str2);
        map.put("username","hjt");
        map.put("timeStr",time);
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(callback);
        soapUtil.execute();
    }
    public void upSign(StudentSign cardStudent,int type){
        StudentSign sign = new StudentSign(cardStudent.getId(), ClassCalendar.getStringMinuts(),ClassCalendar.getCardtime(),type,ClassCalendar.getCardtime(),cardStudent.getCardnum(),"");
        CardDao.updateSign(sign);
        BaseApplication.getDaoInstant().clear();
        intent.setAction(Constant.ERR);
        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 打卡数据上传给后台成功");
        Log.e("ATG","打卡数据上传给后台成功");
        sendBroadcast(intent);
    }
    class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("获取远程连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName nme) {
            RemoteService.this.startService(new Intent(RemoteService.this,
                    LocalService.class));
            RemoteService.this.bindService(new Intent(RemoteService.this,
                    LocalService.class), conn, Context.BIND_IMPORTANT);
        }
    }
    public void Heartbeat(){
        String time= ClassCalendar.getCardtime();
        String namespace = "http://www.gcihjt.com/";//namespace http://www.gcihjt.com/
        String methodName = "Heartbeat";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        map.put("machineNo",android.os.Build.SERIAL);
        map.put("username","hjt");
        map.put("timeStr",time);
        String md5Value = APPUtlis.getMd5Value("hjt"+time+"256B07301378445C83CB1A4D021FF4C7");
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(new AsyncTaskSoapUtil.Callback() {
            @Override
            public void onPost(String data) {
                if (data.equals("00")){
                    Log.e("ATG","心跳包成功");
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 心跳包成功");
                    sendBroadcast(intent);
                }else {
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+":心跳包失败 "+data);
                    sendBroadcast(intent);
                    Log.e("ATG"," 心跳包出错"+data);
                }
            }
        });
        soapUtil.execute();
    }
    public void StudentSign(){
        final List<StudentSign> studentSigns = CardDao.querySignId("3");
        final StringBuilder builder=new StringBuilder();
        if (studentSigns.size()!=0){
            builder.append("<RECORDS version=\"1.2\">\t \n");
            for (StudentSign sign:studentSigns){
                builder.append( "<ERRECORD>\n" +
                        "<CLOCKID>"+android.os.Build.SERIAL+"</CLOCKID>\n" +
                        "<CARDID>"+sign.getCardnum()+"</CARDID>\n" +
                        "<DATETIME>"+sign.getTotalTime()+"</DATETIME> \n" +
                        "<BFLAG>2</BFLAG>\n" +
                        "</ERRECORD>\n");
            }
            builder.append("</RECORDS>");
            Timecard(builder.toString(), new AsyncTaskSoapUtil.Callback() {
                @Override
                public void onPost(String data) {
                    if (data.equals("00")){
                        for (StudentSign sign:studentSigns){
                            upSign(sign,0);
                            builder.setLength(0);
                        }
                    }else{
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 打卡数据上传给后台失败  错误:"+data);
                        sendBroadcast(intent);
                    }
                }
            });
        }
    }
    private Bitmap bitmap;
    private String img;
    public void TeacherSign(){
        final List<StudentSign> studentSigns = CardDao.querySignId("3");
        final StringBuilder builder=new StringBuilder();
        if (studentSigns.size()!=0){
            builder.append("<RECORDS version=\"1.2\">\t \n");
            for (StudentSign sign:studentSigns){
                builder.append( "<ERRECORD>\n" +
                        "<CLOCKID>"+android.os.Build.SERIAL+"</CLOCKID>\n" +
                        "<CARDID>"+sign.getCardnum()+"</CARDID>\n" +
                        "<DATETIME>"+sign.getTotalTime()+"</DATETIME> \n" +
                        "<BFLAG>2</BFLAG>\n" +
                        "</ERRECORD>\n");
            }
            builder.append("</RECORDS>");
            Timecard(builder.toString(), new AsyncTaskSoapUtil.Callback() {
                @Override
                public void onPost(String data) {
                    if (data.equals("00")){
                        TeacherFace();
                        builder.setLength(0);
                    }else{
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 打卡数据上传给后台失败  错误:"+data);
                        sendBroadcast(intent);
                    }
                }
            });
        }
    }
    public void TeacherFace(){
        List<StudentSign> studentSigns = CardDao.querySign();
        for ( final StudentSign sign:studentSigns){
            if (sign.getSigntype()==3){
                final File file=new File(Environment.getExternalStorageDirectory().getPath()+"/Face/"+sign.getCardnum()+ClassCalendar.getIntDay()+".te");
                if (file.exists()){
                    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                    img = APPUtlis.bitmapToBase64(bitmap);
                }else {
                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.no_face);
                    img = APPUtlis.bitmapToBase64(bitmap);
                }
                OkhttPost.Card(sign.getId(), img, new OkhttPost.Callback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                                    Log.e("Date","错误"+e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            Log.e("Face",response);
                            Gson gson=new Gson();
                            ResultFy resultFy = gson.fromJson(response, ResultFy.class);
                            if (resultFy.Code==0){
                                sign.setSigntype(1);
                                file.delete();
                            }else{
                                sign.setSigntype(0);
                            }
                            CardDao.updateSign(sign);
                        }catch (Exception e){}
                    }
                },sign.getUrl(),sign.getCardtime());
            }
        }
    }

}